/**
 * Created by IntelliJ IDEA.
 * User: 12
 * Date: 12-5-3
 * Time: 上午9:29
 * To change this template use File | Settings | File Templates.
 */
$(function(){
    $('#add').dialog({
        title:'添加',
        width:600,
        height:360,
        modal:true,
        closed:true,
        //draggable:false,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:okHandler
        },{
            text:'取消',
            handler:function(){
                $('#add').dialog('close');
            }
        }]
    });

    $('#device_query').dialog({
        title:'查询',
        width:380,
        height:140,
        modal:true,
        closed:true,
        //draggable:false,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:searchHandler
        },{
            text:'取消',
            handler:function(){
                $('#device_query').dialog('close');
            }
        }]
    });

    function okHandler(){
        var did = $("#add_form input[name='id']").val();
        if(did) {
            reqDevice();
            return;
        }

        var formworkId = $("#add_form input[name='formwork.id']").val();
        if(!formworkId || formworkId == ''){
            $.messager.alert('提示','请选择模板','info');
            return ;
        }
        buildInitTerTreeData();//初始化弹窗的树
        $('#device_init_ter_dg').dialog('open');
        //reqDevice();
    };

    function reqDevice() {
        $.messager.progress()
        $('#add_form').form('submit',{
            onSubmit: function(){
                var formworkId = $("#add_form input[name='formwork.id']").val();
                if(!formworkId || formworkId == ''){
                    $.messager.progress('close');

                    $.messager.alert('提示','请选择模板','info');
                    return false;
                }
                var a = $(this).form('validate');
                if(!a) {
                    $.messager.progress('close');
                }
                return a;
            },
            success: function(data) {
                var data = eval('('+data+')');
                if (data.status == '1'){
                    $('#add').dialog('close');      // close the dialog
                    //var node = $('#tt').tree('getSelected');
                    //if (node){
                    //    $('#tt').tree('reload', node.target);
                    // } else {
                    $('#client_tab').datagrid('reload');
                    //}
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
                $.messager.progress('close');
            }

        });
    }

    function searchHandler() {
        var selected = $('#tt').tree('getSelected');
        var name = $("#device_name") ;
        $('#device_query').dialog('close');
        if(!selected) {
            return;
        }
        $('#client_tab').datagrid({
            url:$("#devicesUrl").val() ,
            queryParams:{areaId:selected.id,device_name:name.val()}
        })
    }

    $('#add_area').dialog({
        title:'添加',
        width:380,
        height:200,
        modal:true,
        closed:true,
        //draggable:false,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:okAreaHandler
        },{
            text:'取消',
            handler:function(){
                $('#add_area').dialog('close');
            }
        }]
    });

    function okAreaHandler(){
        $('#add_area_form').form('submit',{
            onSubmit: function(){
                return $(this).form('validate');
            },
            success: function(data) {
                var data = eval('('+data+')');
                if (data.status == '1'){
                    $('#add_area').dialog('close');      // close the dialog
                    //var node = $('#tt').tree('getSelected');
                    //if (node){
                    //    $('#tt').tree('reload', node.target);
                    // } else {
                    $('#tt').tree('reload');
                    //}
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
    };

    $('#tt').tree({
        onClick: function(node){
            if(!node) {
                return;
            }
            $('#client_tab').datagrid({
                url:$("#devicesUrl").val() ,
                queryParams:{areaId:node.id}
            })
        }
    });

    $(".client-add").live('click',function(){
        var selected = $('#tt').tree('getSelected');
        $('#add_area').dialog('open').dialog('setTitle','添加');
        $('#add_area').dialog('open');
        $('#add_area_form').form("clear");
        $("#parentName").val("根节点") ;
        if (selected){
            $("#parentId").val(selected.id) ;
            $("#parentName").val(selected.text) ;
        }
    }) ;


    $(".client-update").live('click',function(){
        var selected = $('#tt').tree('getSelected');

        if (selected){
            var parentNode =  $('#tt').tree('getParent',selected.target);
            $('#add_area').dialog('open').dialog('setTitle','编辑');
            $('#add_area_form').form("clear");
            if(parentNode) {
                $("#parentId").val(parentNode.id) ;
                $("#parentName").val(parentNode.text) ;
            }
            $("#area_name").val(selected.text) ;
            $("#area_id").val(selected.id) ;
        }
    }) ;
    $(".client-delete").live('click',function(){
        var row = $('#tt').tree('getSelected');
        if (row){
            $.messager.confirm('提示','确定删除该记录?',function(r){
                if (r){
                    $.post($('#areaDeleteUrl').val(),{id:row.id},function(result){
                        if (result.status == '1'){
                            $('#tt').tree('reload'); // reload the user data
                        } else {
                            $.messager.show({ // show error message
                                title: 'Error',
                                msg: result.msg
                            });
                        }
                    },'json');
                }
            });
        }

    } );

    function lstAdd(){
        var selected = $('#tt').tree('getSelected');
        $('#add').dialog('open').dialog('setTitle','添加');
        $('#add').dialog('open');
        $('#add_form').form("clear");
        if (selected){
            $("#areaId").val(selected.id) ;
            $("#areaName").val(selected.text) ;
            var formwork = $("#add_form input[name='formwork.id']");
            var p = formwork.parent();
            p.next(".d-formwork-name").remove();
            p.show();
        }
    }
    function lstUpdate() {
        var selected = $('#client_tab').datagrid('getSelected');

        if (selected){
            var parentNode =  $('#tt').tree('getSelected');
            $('#add').dialog('open').dialog('setTitle','编辑');
            $('#add_form').form("clear");
            $('#add_form').form('load',selected);
            if(parentNode) {
                $("#areaId").val(parentNode.id) ;
                $("#areaName").val(parentNode.text) ;
            }
            var formwork = $("#add_form input[name='formwork.id']");
            var p = formwork.parent();
            p.next(".d-formwork-name").remove();
            if(selected.formworkId){
                p.hide();
                p.after("<span class='d-formwork-name'>"+selected.formworkName+"</span>")
            }else{
                p.show();
            }
            formwork.val(selected.formworkId)

            $('#add').dialog('open')
        }
    }

    function lstDelete(){
        var row = $('#client_tab').datagrid('getSelected');
        if (row){
            $.messager.confirm('提示','确定删除该记录?',function(r){
                if (r){
                    $.post($('#deleteUrl').val(),{id:row.id},function(result){
                        if (result.status == '1'){
                            $('#client_tab').datagrid('reload'); // reload the user data
                        } else {
                            $.messager.show({ // show error message
                                title: 'Error',
                                msg: result.msg
                            });
                        }
                    },'json');
                }
            });
        }
    }

    function lstSearch(){
        $('#device_query').dialog('open')

    }


    $('#client_tab').datagrid({
        title:'设备列表',
        singleSelect:true,
        idField:'id',
        pagination:true,
        columns:[[
            {field:'name',title:'名称',width:100,formatter:function(value,rec){
                return "<a href='javascript:void 0' class='device_selected_cla'>"+value+"</span>";
            }},
            {field:'code',title:'编码',width:100},
            {field:'location.addr',title:'位置',width:140}
        ]],
        onBeforeLoad:function(){
            $(this).datagrid('rejectChanges');
        },
        onClickRow:function(rowIndex,rowData) {
            $('#btnedit').linkbutton('enable');
            $('#btnremove').linkbutton('enable');

        },
        rownumbers:true,
        toolbar:[{
            id:'btnadd',
            text:'添加',
            iconCls:'icon-add',
            handler:lstAdd
        },{
            id:'btnedit',
            text:'编辑',
            disabled:true,
            iconCls:'icon-edit',
            handler:lstUpdate
        },'-',{
            id:'btnremove',
            text:'删除',
            disabled:true,
            iconCls:'icon-remove',
            handler:lstDelete
        },'-',{
            id:'btnquery',
            text:'查询',
            iconCls:'icon-search',
            handler:lstSearch
        }]
    });

    $('#device_init_ter_dg').dialog({
        title:'初始化端子盘',
        width:400,
        height:400,
        modal:true,
        closed:true,
        //draggable:false,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:initTer
        },{
            text:'取消',
            handler:function(){
                $('#device_init_ter_dg').dialog('close');
            }
        }]
    });

    function initTer() {
        var acount = $('#device_init_ter_dg').data('acount');
        var bcount = $('#device_init_ter_dg').data('bcount');
        acount = acount?parseInt(acount):0;
        bcount = bcount?parseInt(bcount):0;
        var rh = '';
        var zgStr = '';
        var pxStr = '';
        for(var i=1;i<acount+1;i++) {
            var r = $('#device_init_ter_dg').data("a"+i+"_jk");
            $('#device_init_ter_dg').removeData("a"+i+"_jk")
            if(r){

                if(r.zg){
                    if(zgStr && zgStr != ''){
                        zgStr +=',';
                    }
                    var _zg = r.zg;
                    var __zgs = _zg.split(',');
                    for(var x=0;x<__zgs.length;x++){
                        if(zgStr && zgStr != ''){
                            zgStr +=',';
                        }
                        zgStr += "a"+i+'_'+ __zgs[x];
                    }
                }
                if(r.px){
                    if(pxStr && pxStr != ''){
                        pxStr +=',';
                    }
                    var _px = r.px;
                    var __pxs = _px.split(',')
                    for(var x=0;x<__pxs.length;x++){
                        if(pxStr && pxStr != ''){
                            pxStr +=',';
                        }
                        pxStr += "a"+i+'_'+ __pxs[x];
                    }
                }

                continue;
            }
            if(rh || rh != ''){
                rh += ",";
            }
            rh += "a"+i;
        }
        for(var i=1;i<bcount+1;i++) {
            var r = $('#device_init_ter_dg').data("b"+i+"_jk");
            $('#device_init_ter_dg').removeData("b"+i+"_jk")
            if(r){
                if(r.zg){
                    if(zgStr && zgStr != ''){
                        zgStr +=',';
                    }
                    var _zg = r.zg;
                    var __zgs = _zg.split(',');
                    for(var x=0;x<__zgs.length;x++){
                        if(zgStr && zgStr != ''){
                            zgStr +=',';
                        }
                        zgStr += "b"+i+'_'+ __zgs[x];
                    }
                }
                if(r.px){
                    if(pxStr && pxStr != ''){
                        pxStr +=',';
                    }
                    var _px = r.px;
                    var __pxs = _px.split(',')
                    for(var x=0;x<__pxs.length;x++){
                        if(pxStr && pxStr != ''){
                            pxStr +=',';
                        }
                        pxStr += "b"+i+'_'+ __pxs[x];
                    }
                }
                continue;
            }
            if(rh || rh != ''){
                rh += ",";
            }
            rh += "b"+i;
        }
        if(rh && rh !='') {
            $.messager.alert('提示','请选择'+rh+'区主干或配线','info');
            return;
        }
        $("#ter_zg").val(zgStr);
        $("#ter_px").val(pxStr);
        $('#device_init_ter_dg').dialog('close');

        reqDevice();
    }

    function buildInitTerTreeData() {
        $("#device_init_ter_center").html('');
        var url = $('#formworkTreeDataUrl').val();
        //$('#cc').combotree('getValue');
        var formworkId = $("#add_form input[name='formwork.id']").val();

        $.getJSON(url,{id:formworkId,r:Math.random()},function(data){
            buildInitTerTree(_buildTreeData(data))
        })  ;
    }
    /**
     * 初始化端子中需要的树
     * @param treedata
     */
    function buildInitTerTree(treedata) {
        var _tree = $('#device_init_ter_tree') ;
        _tree.tree({
            data:treedata ,
            onClick: _terTreeClick
        });
    }

    function _terTreeClick(node) {
        var id = node.id;
        var _data = $('#device_init_ter_dg').data(id)  ;
        if(!_data) {
            return;
        }
        var _zg ='';
        var _px = '';
        var r = $('#device_init_ter_dg').data(id+"_jk");
        if(r) {
            if(r.zg){
                _zg = r.zg
            }
            if(r.px) {
                _px = r.px;
            }
        }
        
        var category = _data['category'];
        var quantity = _data['quantity'];
        quantity = parseInt(quantity);
        //var htm = $("#init_ter_htm").val()  ;
        var htm = "<table class=\"init_ter_tab\">";
            htm += "<tr><th>盘符</th><th>主干区</th><th>配线区</th></tr>";

        var __zgval = ''  ;
        for(var i=0;i<quantity;i++){
            var c = String.fromCharCode(65+i);
            var zgchk = '';
            var pxchk = '';

            var _zgss = _zg.split(",");
            for(var m=0;m<_zgss.length;m++){
                if(_zgss[m] == c){
                    zgchk = "checked=true";
                    break;
                }
            }

            var _pxss = _px.split(",");
            for(var n=0;n<_pxss.length;n++){
                if(_pxss[n] == c){
                    pxchk = "checked=true";
                    break;
                }
            }
            if(!zgchk && !pxchk) {
                zgchk = "checked=true";
                if(__zgval) {
                    __zgval += ',';
                }
                __zgval += c
            }
            htm += "<tr align=\"center\"><td>"+c+"</td><td><input type=\"radio\" class='zg_ter' name=\"zg_ter_"+i+"\" "+zgchk+" value=\""+c+"\"></td><td><input type=\"radio\" name=\"zg_ter_"+i+"\" "+pxchk+" class='px_ter'value=\""+c+"\"></td></tr>"
        }
        htm += "</table>"    ;
        if(!r) {
            $('#device_init_ter_dg').data(id+"_jk", {zg:__zgval});
        }
        $("#device_init_ter_center").html(htm);
    }

    $(".zg_ter").live('change',function(){
         var t = $(this);
        var chk = t.attr("checked");
        var _tree = $('#device_init_ter_tree').tree('getSelected') ;
        var jk = _tree.id;
        jk +="_jk"
        var jkres = $('#device_init_ter_dg').data(jk);
        if(!jkres) {
            $('#device_init_ter_dg').data(jk,{'zg':t.val()});
        }else{
            var v = jkres['zg'];
            if(chk) {
                if(v){
                    jkres['zg']=v+','+t.val();
                }else{
                    jkres['zg'] = t.val();
                }
            }else{
                var _v = v.split(',');
                for(var y=0;y<_v.length;y++){
                    if(t.val() == _v[y]){
                        _v.splice(y,1);
                        break;
                    }
                }
                jkres['zg']=_v.toString();
            }


        }
        if(chk && jkres && jkres['px']) {
            var zgv = jkres['px'];
            var zgvs = zgv.split(',');
            for(var z=0;z<zgvs.length;z++){
                if(t.val() == zgvs[z]){
                    zgvs.splice(z,1);
                    jkres['px'] = zgvs.toString();
                    break;
                }
            }
        }
    });
    $(".px_ter").live('change',function(){
        var t = $(this);
        var chk = t.attr("checked");
        var _tree = $('#device_init_ter_tree').tree('getSelected') ;
        var jk = _tree.id;
        jk +="_jk"
        var jkres = $('#device_init_ter_dg').data(jk);
        if(!jkres) {
            if(chk) {
                $('#device_init_ter_dg').data(jk,{'px':t.val()});
            }
        }else{
            var v = jkres['px'];
            if(chk) {
                if(v) {
                    jkres['px']=v+','+t.val();
                } else{
                    jkres['px']=t.val();
                }
            }else{
                var _v = v.split(',');
                for(var y=0;y<_v.length;y++){
                    if(t.val() == _v[y]){
                        _v.splice(y,1);
                        break;
                    }
                }
                jkres['px']=_v.toString();
            }
        }
        if(chk && jkres && jkres['zg']) {
            var zgv = jkres['zg'];
            var zgvs = zgv.split(',');
            for(var z=0;z<zgvs.length;z++){
                if(t.val() == zgvs[z]){
                    zgvs.splice(z,1);
                    jkres['zg'] = zgvs.toString();
                    break;
                }
            }
        }
    });
    /**
     * 生成树形需要的数据格式.
     *
     * @param map 后台返回的格式
     */
    function _buildTreeData(map) {
        var aname = map.composition_a;
        var bname = map.composition_b;
        var anames = aname.split('_');
        var bnames;
        var acount = anames[1];
        var bcount = 0;
        var treeDataA = [acount];
        var treeDataB = [];
        $('#device_init_ter_dg').data('acount',acount);
        if(bname) {
            bnames = bname.split('_');
            bcount = bnames[1];
            treeDataB = [bcount];
            $('#device_init_ter_dg').data('bcount',bcount);
        }
        var treeData = [2] ;
        $('#device_init_ter_dg').data("a",aname);//A区,布局名称
        $('#device_init_ter_dg').data("b",bname); //B区,布局名称

        for(var i=1;i<=acount;i++){
            var _data = map['a'+i];
            $('#device_init_ter_dg').data('a'+i,_data); //a区块，对应的数据如：a1:{category:'',quantity:1}
            treeDataA[i-1]={id:'a'+i,text:'机框'+i}
        }
        for(var i=1;i<=bcount;i++){
            var _data = map['b'+i];
            $('#device_init_ter_dg').data('b'+i,_data); //b区块，对应的数据如：a1:{category:'',quantity:1}
            treeDataB[i-1]={id:'b'+i,text:'机框'+i}
        }
        if(!treeDataB)  {
            treeDataB = [];
        }
        treeData[0] = {id:'a0',text:'A面',children:treeDataA};
        if(treeDataB && treeDataB.length > 0){
            treeData[1] = {id:'b0',text:'B面',children:treeDataB};
        }
        return treeData;
    }
})

